<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>运输计划调试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
            background-color: #f5f5f5;
        }

        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        h1,
        h2 {
            color: #333;
            border-bottom: 2px solid #409EFF;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }

        input,
        select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        button {
            background: #409EFF;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-right: 10px;
        }

        button:hover {
            background: #337ecc;
        }

        .result {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            background: #fafafa;
            white-space: pre-wrap;
            font-family: monospace;
        }

        .error {
            color: #F56C6C;
            background: #FEF0F0;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }

        .success {
            color: #67C23A;
            background: #F0F9FF;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>🔍 运输计划调试工具</h1>

        <div class="form-group">
            <label for="billNo">运单编号:</label>
            <input type="text" id="billNo" placeholder="例如: YD202412250001" value="YD202412250001">
        </div>

        <div class="form-group">
            <label for="departureCity">出发城市:</label>
            <input type="text" id="departureCity" placeholder="例如: 长春" value="长春">
        </div>

        <div class="form-group">
            <label for="destinationCity">目的城市:</label>
            <input type="text" id="destinationCity" placeholder="例如: 天津" value="天津">
        </div>

        <button onclick="testQueryPlan()">测试查询运输计划</button>
        <button onclick="testGeneratePlan()">测试生成运输计划</button>
        <button onclick="testCityTransitAPI()">测试城市运输分析API</button>
        <button onclick="clearResults()">清空结果</button>
    </div>

    <div class="container">
        <h2>📋 调试结果</h2>
        <div id="result"></div>
    </div>

    <script>
        const baseURL = 'http://localhost:8080';

        function showResult (title, data) {
            const resultDiv = document.getElementById('result');
            resultDiv.innerHTML = `
                <h3>${title}</h3>
                <div class="result">${JSON.stringify(data, null, 2)}</div>
            `;
        }

        function showError (message) {
            document.getElementById('result').innerHTML = `<div class="error">❌ 错误: ${message}</div>`;
        }

        function showSuccess (message) {
            document.getElementById('result').innerHTML = `<div class="success">✅ ${message}</div>`;
        }

        function clearResults () {
            document.getElementById('result').innerHTML = '';
        }

        // 测试查询运输计划
        async function testQueryPlan () {
            const billNo = document.getElementById('billNo').value;
            if (!billNo) {
                showError('请输入运单编号');
                return;
            }

            try {
                console.log('查询运输计划，运单编号:', billNo);
                const response = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
                const data = await response.json();

                console.log('查询响应:', data);
                showResult('查询运输计划结果', data);

                if (data.code === 200) {
                    if (data.rows && data.rows.length > 0) {
                        showSuccess(`查询成功，找到 ${data.rows.length} 条运输计划记录`);
                    } else {
                        showError('未找到运输计划记录');
                    }
                } else {
                    showError(data.msg || '查询失败');
                }
            } catch (error) {
                console.error('查询异常:', error);
                showError('查询异常: ' + error.message);
            }
        }

        // 测试生成运输计划
        async function testGeneratePlan () {
            const billNo = document.getElementById('billNo').value;
            const departureCity = document.getElementById('departureCity').value;
            const destinationCity = document.getElementById('destinationCity').value;

            if (!billNo || !departureCity || !destinationCity) {
                showError('请填写完整信息');
                return;
            }

            try {
                // 1. 调用城市运输分析接口
                console.log('调用城市运输分析接口...');
                const analysisResponse = await fetch(`${baseURL}/pack/locationLog/analysis/cityTransit?departureCity=${encodeURIComponent(departureCity)}&destinationCity=${encodeURIComponent(destinationCity)}`);
                const analysisData = await analysisResponse.json();

                console.log('城市运输分析响应:', analysisData);
                showResult('城市运输分析结果', analysisData);

                if (analysisData.code !== 200) {
                    showError('获取城市运输分析数据失败: ' + (analysisData.msg || '未知错误'));
                    return;
                }

                if (!analysisData.data || !analysisData.data.passedCities || analysisData.data.passedCities.length === 0) {
                    showError('未获取到有效的运输路径数据');
                    return;
                }

                // 2. 保存运输计划
                console.log('开始保存运输计划...');
                const passedCities = analysisData.data.passedCities;
                const saveResults = [];

                for (let i = 0; i < passedCities.length; i++) {
                    const cityInfo = passedCities[i];

                    let nodeType = '途经点';
                    if (i === 0) {
                        nodeType = '起点';
                    } else if (i === passedCities.length - 1) {
                        nodeType = '终点';
                    }

                    const planData = {
                        waybillId: 1,
                        billNo: billNo,
                        locatorId: 1,
                        locatorCode: 'LOC001',
                        province: cityInfo.provinceName || '',
                        city: cityInfo.cityName || '',
                        district: '',
                        estimatedDuration: cityInfo.averageStayTime || 0,
                        nodeType: nodeType,
                        passOrder: cityInfo.passOrder || (i + 1)
                    };

                    console.log('保存运输计划数据:', planData);

                    const saveResponse = await fetch(`${baseURL}/system/plan`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(planData)
                    });
                    const saveResult = await saveResponse.json();

                    saveResults.push({
                        index: i,
                        planData: planData,
                        result: saveResult
                    });

                    console.log(`第${i + 1}条保存结果:`, saveResult);
                }

                showResult('运输计划保存结果', saveResults);

                // 3. 重新查询验证
                setTimeout(() => {
                    testQueryPlan();
                }, 1000);

            } catch (error) {
                console.error('生成运输计划异常:', error);
                showError('生成运输计划异常: ' + error.message);
            }
        }

        // 测试城市运输分析API
        async function testCityTransitAPI () {
            const departureCity = document.getElementById('departureCity').value;
            const destinationCity = document.getElementById('destinationCity').value;

            if (!departureCity || !destinationCity) {
                showError('请填写出发城市和目的城市');
                return;
            }

            try {
                console.log('调用城市运输分析API...');
                const response = await fetch(`${baseURL}/pack/locationLog/analysis/cityTransit?departureCity=${encodeURIComponent(departureCity)}&destinationCity=${encodeURIComponent(destinationCity)}`);
                const data = await response.json();

                console.log('API响应:', data);
                showResult('城市运输分析API结果', data);

                if (data.code === 200) {
                    showSuccess('API调用成功');
                } else {
                    showError(data.msg || 'API调用失败');
                }
            } catch (error) {
                console.error('API调用异常:', error);
                showError('API调用异常: ' + error.message);
            }
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function () {
            console.log('运输计划调试页面已加载');
        });
    </script>
</body>

</html>